package com.guijianpan.demo.repository.specifications;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import com.guijianpan.demo.domain.Demo;

public class DemoSpecs {

	public static Specification<Demo> equalBalanceAndlikedemoName(
			final Demo demo) {

		return new Specification<Demo>() {
			@Override
			public Predicate toPredicate(Root<Demo> root,
					CriteriaQuery<?> query, CriteriaBuilder builder) {

				// add for not null
				Predicate predicate = builder.and();

				// condition one
				if (demo.getIsDeleted() != null) {
					predicate = builder.and(builder.equal(
							root.get("isDeleted"), demo.getIsDeleted()));
				}
				// condition two
				if (demo.getName() != null) {
					String likePattern = getLikePattern(demo.getName());
					
					predicate = builder.and(predicate, builder.like(
							builder.lower(root.<Demo> get("demo").<String> get(
									"name")), likePattern));
				}

				return predicate;
			}

			private String getLikePattern(final String searchTerm) {
				StringBuilder pattern = new StringBuilder();
				pattern.append("%");
				pattern.append(searchTerm.toLowerCase());
				pattern.append("%");
				return pattern.toString();
			}
		};
	}
}
